package com.hmyd.hmyd_android.crypto;

import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 完全替代play.libs.Crypto
 * 
 * 但不应该轻易修改此类的任何加密算法！！！
 * 
 * 
 * 可使用configuration.getProperty("application.secret")获取应用密钥作为secret参数
 */
public class Crypto {
	//chen56:copy from playframework
    static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    public static final String PRIVATEKEY = "8$hmyd_android#8";
    
    
     /**
     * chen56:copy from playframework
     * Define a hash type enumeration for strong-typing
     */
    public enum HashType {
        MD5("MD5"),
        SHA1("SHA-1"),
        SHA256("SHA-256"),
        SHA512("SHA-512");
        private String algorithm;
        HashType(String algorithm) { this.algorithm = algorithm; }
        @Override public String toString() { return this.algorithm; }
    }

    /**
	 * chen56:copy from playframework
     * Encrypt a String with the AES encryption standard. Private key must have a length of 16 bytes
     * @param value The String to encrypt
     * @param privateKey The key used to encrypt
     * @return An hexadecimal encrypted string
     */
    public static String encryptAES(String value, String privateKey) {
        try {
            byte[] raw = privateKey.getBytes(Charset.forName("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return Codec2.byteToHexString(cipher.doFinal(value.getBytes(Charset.forName("UTF-8"))));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    /**
	 * chen56:copy from playframework
     * Decrypt a String with the AES encryption standard. Private key must have a length of 16 bytes
     * @param value An hexadecimal encrypted string
     * @param privateKey The key used to encrypt
     * @return The decrypted String
     */
    public static String decryptAES(String value, String privateKey) {
        try {
            byte[] raw = privateKey.getBytes(Charset.forName("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            return new String(cipher.doFinal(Codec2.hexStringToByte(value)),Charset.forName("UTF-8"));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    
}